package com.agynamix.scala.mi

import _root_.java.io.File
import _root_.javax.script.ScriptException

class TVSeriesFileProcessor extends MediaFileProcessor {

  def process(mediaFile: File): ITunesProcessResult = {
//    String fullName = removeExtension(mediaFile.getName())
    val episodeName = getEpisodeName(mediaFile)
    val seriesNumber = getSeriesNumber(mediaFile)
    val episodeNumber = getEpisodeNumber(mediaFile)
    val seriesName = getSeriesName(mediaFile)
    val appleFileName = mediaFile.getAbsolutePath()
    println("Found: " + appleFileName + "; episode=" + seriesNumber+"X"+episodeNumber+", name="+episodeName + ", series=" + seriesName)

    try {
        return addSeriesToItunes(appleFileName, seriesName, episodeName, seriesNumber, episodeNumber)
    } catch {
      case e => println("Could not import media file: "+appleFileName+", Error: "+e.getMessage)
                return new ITunesProcessResult(false, "")
    }

  }

  @throws(classOf[ScriptException])
  def addSeriesToItunes(appleFileName: String, seriesName: String, episodeName: String, seriesNumber: Int, episodeNumber: Int): ITunesProcessResult = {
    val sb = new StringBuilder()
    sb.append("set iTunesFile to POSIX file \"" + appleFileName + "\"\n")
    sb.append("tell application \"iTunes\"\n")
    sb.append("copy (add iTunesFile) to newMovie\n")
    sb.append("set (video kind of newMovie) to TV show\n")
    sb.append("set ((season number) of newMovie) to ("+seriesNumber+")\n")
    sb.append("set (show of newMovie) to \""+seriesName+" "+seriesNumber+"\"\n")

    if (!isEmpty(episodeName))
    {
      sb.append("set (name of newMovie) to \""+episodeNumber+" "+episodeName+"\"\n")
    } else {
      sb.append("set (name of newMovie) to \"Episode "+episodeNumber+"\"\n")
    }

    sb.append("set ((episode ID) of (newMovie)) to \"S"+seriesNumber+"E"+episodeNumber+"\"\n")
    sb.append("set ((episode number) of newMovie) to "+episodeNumber+"\n")
    sb.append("set ((sort show) of (newMovie)) to \""+seriesName+" S"+seriesNumber+"E"+episodeNumber+"\"\n")
    sb.append("set pid to newMovie's persistent ID\n")

    sb.append("end tell");

//    System.out.println(sb.toString());

    new ITunesProcessResult(true, scriptEngine.eval(sb.toString()).toString)
  }

  /**
   * Name of the whole series
   * @param mediaFile the path to a specific file:
   * TV Series/<Name of Series>/S<number>/<Episode Name>
   * @return
   */
  def getSeriesName(mediaFile: File): String = {
    return mediaFile.getParentFile().getParentFile().getName()
  }


  def getEpisodeNumber(mediaFile: File): Int = {
    val episodeFull = mediaFile.getName()
    val pos = episodeFull.indexOf("-")
    if (pos > -1)
    {
      val episodePrefix = episodeFull.substring(0, pos).trim()
      val episodeNumber = new StringBuilder()
      var i = episodePrefix.length-1
      var isStop = false
      do {
        if (Character.isDigit(episodePrefix.charAt(i)))
        {
          episodeNumber.insert(0, episodePrefix.charAt(i))
        } else {
          isStop = true
        }
        i -= 1
      } while (i>0 && !isStop)
      
      if (episodeNumber.length > 0)
      {
        return Integer.parseInt(episodeNumber.toString())
      }

    }
    return 1
  }


  def getSeriesNumber(mediaFile: File): Int = {

    val seriesDirectory = mediaFile.getParentFile()

    if (seriesDirectory.isDirectory())
    {
      val season = seriesDirectory.getName()
      if (season.startsWith("S")) {
        try {
        return Integer.parseInt(season.substring(1))
        } catch {
          case e => System.out.println("Could not read seasonNumber for File "+mediaFile)
        }
      }
    }
    return 1
  }


  def getEpisodeName(mediaFile: File): String = {
    val episodeFull = removeExtension(mediaFile.getName())
    val pos = episodeFull.indexOf("-")
    if (pos > -1)
    {
      val episodeName = episodeFull.substring(pos+1).trim()
      return episodeName
    }
    return episodeFull
  }

}
